package com.alibaba.citrus.cr.order.open.api.facade.service.handler;

import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crunifiedinventory.dto.response.AllocateOrderCreateResponse;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCreateRequest;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateOrderTypeEnum;
import com.epoch.app.mninventorycenter.model.dto.*;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * 同公司或跨公司调拨单创建
 *
 * @author mingyang
 * @since 2024/01/04
 */
@Component
public class SameOrCrossCompanyHandler extends AbstractAllocateOrderCreateHandler {
    private Log log = Log.getLogger(SameOrCrossCompanyHandler.class);


    @Override
    public Boolean support(TransferOrderCreateRequest request) {
        return Objects.equals(AllocateOrderTypeEnum.SAME_COMPANY.getType(),request.getTransferOrderType())
                || Objects.equals(AllocateOrderTypeEnum.CROSS_COMPANY.getType(),request.getTransferOrderType());
    }

    @Override
    public TransferOrderCreateResponse handle(TransferOrderCreateRequest request, Map<String, ScItemResponse> scItemInfoMap, WarehouseQueryResponse receiveLogicWareId, WarehouseQueryResponse deliveryLogicWareId) {
        AllocateOrderCreateRequest allocateOrderCreateRequest = getAllocateOrderCreateRequest(request,scItemInfoMap, receiveLogicWareId, deliveryLogicWareId);
        allocateOrderCreateRequest.setFeatures(getFeatures(receiveLogicWareId, deliveryLogicWareId));
        log.info("createAllocateApplyOrder.createAllocateOrderApi,SAME_COMPANY.CROSS_COMPANY,request:{}", JSON.toJSON(allocateOrderCreateRequest));
        Result<AllocateOrderCreateResponse> allocateOrderCreateResult = allocateOrderWriteService.createAllocateOrderApi(allocateOrderCreateRequest);
        log.info("createAllocateApplyOrder.createAllocateOrderApi,response:{}", JSON.toJSON(allocateOrderCreateResult));
        if(!allocateOrderCreateResult.isSuccess()){
            throw new FacadeException(allocateOrderCreateResult.getErrorCode(), allocateOrderCreateResult.getMessage());
        }
        AllocateOrderCreateResponse result = allocateOrderCreateResult.getResult();
        return getAllocateOrderCreateResponse(result.getCode(), result.getThirdAllocateOrderId(), result.getAllocateOrderDetailList());
    }

}
